import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DeepPartial, Repository, FindOptionsWhere } from 'typeorm';
import { Schedule } from './models/schedule.entity';
@Injectable()
export class ScheduleService {
  constructor(
    @InjectRepository(Schedule)
    private readonly ScheduleRepository: Repository<Schedule>,
  ) {}

  async create(entity: DeepPartial<Schedule>): Promise<boolean> {
    const res = await this.ScheduleRepository.save(
      this.ScheduleRepository.create(entity),
    );
    if (res) {
      return true;
    }
    return false;
  }

  async findById(id: string): Promise<Schedule> {
    return this.ScheduleRepository.findOne({
      where: {
        id,
      },
    });
  }

  async updateById(
    id: string,
    entity: DeepPartial<Schedule>,
  ): Promise<boolean> {
    const existEntity = await this.findById(id);
    if (!existEntity) {
      return false;
    }
    Object.assign(existEntity, entity);
    const res = await this.ScheduleRepository.save(existEntity);
    if (res) {
      return true;
    }
    return false;
  }

  // 获取所有的课程表
  async findAllSchedules({
    where,
  }: {
    where: FindOptionsWhere<Schedule>;
  }): Promise<[Schedule[], number]> {
    return this.ScheduleRepository.findAndCount({
      where,
      order: {
        startTime: 'ASC',
      },
      relations: ['course'],
      // relations: ['course','course.teachers'] // 最新的
    });
  }

  async findSchedules({
    start,
    length,
    where,
  }: {
    start: number;
    length: number;
    where: FindOptionsWhere<Schedule>;
  }): Promise<[Schedule[], number]> {
    return this.ScheduleRepository.findAndCount({
      take: length,
      skip: start,
      where,
      order: {
        createdAt: 'DESC',
      },
    });
  }

  // 获取所有的课程表
  // async findAllSchedules({
  //   where,
  // }: {
  //   where: FindOptionsWhere<Schedule>;
  // }): Promise<[Schedule[], number]> {
  //   return this.ScheduleRepository.findAndCount({
  //     where,
  //     order: {
  //       createdAt: 'DESC',
  //     },
  //     relations: [
  //       'course',
  //       'course.teachers',
  //       'scheduleRecords',
  //       'scheduleRecords.student',
  //     ],
  //   });
  // }

  async deleteById(id: string, userId: string): Promise<boolean> {
    const res1 = await this.ScheduleRepository.update(id, {
      deletedBy: userId,
    });
    if (res1) {
      const res = await this.ScheduleRepository.softDelete(id);
      if (res.affected > 0) {
        return true;
      }
    }
    return false;
  }
}
